package xcmg.device.service.company;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.CompanyInvitationCodeDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.CompanyInvitationCodeMapper;
import xcmg.device.dao.mapper.CompanySupplierMapper;
import xcmg.device.dao.mapper.SaleIntentionMapper;
import xcmg.device.dao.mapper.account.ArapMapper;
import xcmg.device.dao.mapper.company.DealerVehicleMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDealerAuthDOMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.infra.CompanyConstants;
import xcmg.device.infra.DateUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.FileUtil;
import xcmg.device.infra.enums.ApplyStatusEnum;
import xcmg.device.infra.enums.CompanyDealerStatusEnum;
import xcmg.device.infra.exception.CommonBusiExceptions;
import xcmg.device.service.basic.CommonGenService;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.basic.MaterialsSearchVO;
import xcmg.device.service.vo.company.AuditApplyVO;
import xcmg.device.service.vo.company.CompanyDealerVO;
import xcmg.device.service.vo.company.CompanyInfoVO;
import xcmg.device.service.vo.company.CompanyRegisterVO;
import xcmg.device.service.vo.company.DealerVehicleExportVO;
import xcmg.device.service.vo.warehouse.WarehouseDealerAuthVO;
import xcmg.device.util.CompanyUtil;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by sqq on 2017/12/22.
 */
@Service
@Slf4j
public class CompanyDealerService {

    @Autowired
    private CompanyUtil companyUtil;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private CompanyInvitationCodeMapper companyInvitationCodeMapper;

    /**
     * add by huhuawei 2018-9-21
     */
    @Autowired
    private WarehouseDealerAuthDOMapper warehouseDealerAuthDOMapper;

    @Autowired
    private CommonGenService commonGenService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private CompanyApplyService companyApplyService;

    @Autowired
    private CompanySupplierMapper companySupplierMapper;
    @Autowired
    private CompanySupplierService companySupplierService;
    @Autowired
    private HttpServletResponse response;

    @Autowired
    private SaleIntentionMapper saleIntentionMapper;

    @Value("${company.setting.inviteExpireDay}")
    private Integer inviteExpireDay;

    @Value("${company.setting.invitationCodeLength}")
    private Integer invitationCodeLength;

    @Value("${spring.file.download.path}")
    private String filePath;

    private String templateDealer = "CompanyDealer.xls";
    @Autowired
    private ArapMapper arapMapper;
    @Autowired
    private DealerVehicleMapper dealerVehicleMapper;

    /**
     * 导出分页大小
     */
    private static final Integer EXPORT_PAGE_SIZE = 1000;

    public ErrorCode insert(CompanyDealerVO companyDealerVO) {
        String textID = commonGenService.textIdWithException();
        companyDealerVO.setDealerOrgId(textID);
        companyDealerVO.setCreateDate(new Date());
        companyDealerVO.setUpdateDate(new Date());
        companyDealerVO.setIsDel(false);
        companyDealerVO.setIsPlatCompany(false);
        CompanyDealerDO companyDealerDO = getDO(companyDealerVO);
        Integer nameCount = companyDealerMapper.nameCount(companyDealerDO);
        if (nameCount > 0) {
            return ErrorCode.DealerNameDuplicated;
        }
        if (companyDealerDO.getDealerCode() != null) {
            Integer codeCount = companyDealerMapper.dealerCodeCount(companyDealerDO);
            if (codeCount > 0) {
                return ErrorCode.DealerCodeDuplicated;
            }
        }
        boolean isYN = companyUtil.isYN(companyDealerDO.getOrgId());
        if (isYN) {
            companyDealerDO.setDealerLevel(1);
            addCompanyDealerDO(companyDealerDO);
            //一步完成、邀请、注册、审核
            return doRegistAndAudit(companyDealerVO, companyDealerDO);
        } else {
            companyDealerDO.setDealerLevel(2);
            return addCompanyDealerDO(companyDealerDO) ? ErrorCode.Success : ErrorCode.Failure;
        }
    }

    /**
     * 一步完成、邀请、注册、审核
     *
     * @param companyDealerVO
     * @param companyDealerDO
     * @return
     */
    private ErrorCode doRegistAndAudit(CompanyDealerVO companyDealerVO, CompanyDealerDO companyDealerDO) {
        CompanyDealerVO companyDealerVO2 = new CompanyDealerVO();
        companyDealerVO2.setId(companyDealerDO.getId());
        ErrorCode code = invite(companyDealerVO2, companyDealerVO.getCreateId());
        if (code.getCode() == ErrorCode.Success.getCode()) {
            CompanyRegisterVO companyRegisterVO = new CompanyRegisterVO();
            companyRegisterVO.setCompanyName(companyDealerDO.getCompanyName());
            companyRegisterVO.setOrgCode(companyDealerDO.getDealerOrgId());
            companyRegisterVO.setInvitationCode(companyDealerVO2.getInvitationCode());

            ErrorCode errorCode = companyInfoService.register(companyRegisterVO);
            if (errorCode.getCode() == ErrorCode.Success.getCode()) {
                AuditApplyVO auditApplyVO = new AuditApplyVO();
                auditApplyVO.setAuditName(companyDealerVO.getCreateName());
                auditApplyVO.setAuditId(companyDealerVO.getCreateId());
                auditApplyVO.setAuditStatus(ApplyStatusEnum.Pass.getCode());
                auditApplyVO.setAuditRemark("云内创建");
                auditApplyVO.setIsSap(0);
                auditApplyVO.setIsBarcode(0);
                auditApplyVO.setApplyId(companyRegisterVO.getApplyId() + "");
                auditApplyVO.setDealerType(companyDealerVO.getDealerType());
                return companyApplyService.audit(auditApplyVO);
            }
            return errorCode;
        }
        return code;
    }

    public boolean addCompanyDealerDO(CompanyDealerDO companyDealerDO) {
        companyDealerDO.setId(commonGenService.longIdWithException());
        return companyDealerMapper.insertWithPK(companyDealerDO) > 0;
    }

    public boolean mergeCompanyDealerDO(CompanyDealerDO companyDealerDO) {
        companyDealerDO.setId(commonGenService.longIdWithException());
        return companyDealerMapper.merge(companyDealerDO) > 0;
    }

//    //同步代理商
//    @Async
//    public void getSap(String orgId) {
//        CompanyInfoVO companyInfoVO = companyInfoService.info(orgId);
//        if (companyInfoVO == null) {
//            LogHelper.error("同步sap代理商时企业不存在", ErrorCode.RequestIdError.getCode());
//            return;
//        }
//        ImportParam importParam = new ImportParam();
//        importParam.setFunction("ZPMSBJ_GET_KUNNR");
//        importParam.setTable("KUNNROUT");
//        Map<String, String> map = new HashMap<>();
//        map.put("VKORG", companyInfoVO.getSapCode());
//        Date date = new Date();
//        DateFormat format = new SimpleDateFormat("yyyyMMdd");
//        map.put("I_PSTMP", format.format(date));
//        importParam.setCommonParamMap(map);
//        importParam.setSapCode(companyInfoVO.getSapCode());
//        LogHelper.monitor("========调用同步代理商接口开始========");
//        OutputParam outputParam = SAPCommonUtil.getData(importParam);
//        LogHelper.monitor("========调用同步代理商接口结束========");
//        if (outputParam == null) {
//            LogHelper.error("sap返回值为null", ErrorCode.RequestIdError.getCode());
//            return;
//        }
//        for (Map<String, String> info : outputParam.getDataList()) {
//            CompanyDealerDO companyDealerDO = new CompanyDealerDO();
//            companyDealerDO.setOrgId(orgId);
//            companyDealerDO.setDealerCode(info.get("KUNNR"));
//            companyDealerDO.setAddress(info.get("ADRNR"));
//            companyDealerDO.setCompanyName(info.get("NAME1"));
//            companyDealerDO.setContactTel(info.get("TELF1_LXR"));
//            companyDealerDO.setContact(info.get("NAME1_LXR"));
//            companyDealerDO.setCustomerGroup(info.get("KDGRP"));
//            companyDealerDO.setPriceGroup(info.get("KONDA"));
//            companyDealerDO.setSaleGroup(info.get("VKGRP"));
//            companyDealerDO.setSaleDept(info.get("VKBUR"));
//            CompanyDealerDO dealerDO = companyDealerMapper.itemByDealerCode(companyDealerDO.getOrgId(), companyDealerDO.getDealerCode());
//            if (dealerDO == null) {
//                companyDealerDO.setDealerOrgId(commonGenService.textIdWithException("同步sap代理商时获取orgId失败"));
//                companyDealerDO.setCreateDate(new Date());
//                companyDealerDO.setUpdateDate(new Date());
//                companyDealerDO.setIsDel(false);
//                companyDealerDO.setIsPlatCompany(false);
//                addCompanyDealerDO(companyDealerDO);
//            } else {
//                companyDealerDO.setUpdateDate(new Date());
//                companyDealerMapper.update(companyDealerDO);
//            }
//        }
//    }


    public ErrorCode update(CompanyDealerVO companyDealerVO) {
        CompanyDealerVO newVO = new CompanyDealerVO();
        BeanUtils.copyProperties(companyDealerVO, newVO);
        newVO.setUpdateDate(new Date());
        newVO.setId(companyDealerVO.getId());
        newVO.setDealerCode(companyDealerVO.getDealerCode());
        newVO.setCompanyName(companyDealerVO.getCompanyName());
        newVO.setShortName(companyDealerVO.getShortName());
        newVO.setAddress(companyDealerVO.getAddress());
        newVO.setZip(companyDealerVO.getZip());
        newVO.setFax(companyDealerVO.getFax());
        newVO.setContact(companyDealerVO.getContact());
        newVO.setContactTel(companyDealerVO.getContactTel());
        newVO.setDealerClassId(companyDealerVO.getDealerClassId());
        newVO.setUpdateId(companyDealerVO.getUpdateId());
        newVO.setOwerId(companyDealerVO.getOwerId());
        newVO.setDepartemntId(companyDealerVO.getDepartemntId());
        newVO.setIsStorage(companyDealerVO.getIsStorage());
        newVO.setDeptId(companyDealerVO.getDeptId());
        CompanyDealerDO companyDealerDO = companyDealerMapper.item(companyDealerVO.getId());
        if (companyDealerDO == null) {
            return ErrorCode.IllegalArument;
        }
        companyDealerDO.setCompanyName(companyDealerVO.getCompanyName());
        Integer nameCount = companyDealerMapper.nameCount(companyDealerDO);
        if (nameCount > 0) {
            return ErrorCode.DealerNameDuplicated;
        }
        if (companyDealerDO.getDealerCode() != null) {
            companyDealerDO.setDealerCode(companyDealerVO.getDealerCode());
            Integer codeCount = companyDealerMapper.dealerCodeCount(companyDealerDO);
            if (codeCount > 0) {
                return ErrorCode.DealerCodeDuplicated;
            }
        }
        //修改客户车辆的客户名称
        dealerVehicleMapper.updateClientNameByClientId(companyDealerVO.getCompanyName(), String.valueOf(companyDealerVO.getId()));
        CompanyDealerDO dealerUpdate = getDO(newVO);
        //如果原来有税率，编辑后没有的税率则将税率字段值清空
        if (companyDealerDO.getTaxRate() != null && dealerUpdate.getTaxRate() == null) {
            dealerUpdate.setCleanTaxRate(true);
        }
        return companyDealerMapper.update(dealerUpdate) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    @Transactional
    public ErrorCode delete(List<Long> ids, String userId) {
        ErrorCode ret = ErrorCode.Success;
        for (Long id : ids
        ) {
            CompanyDealerVO newVO = new CompanyDealerVO();
            newVO.setUpdateDate(new Date());
            newVO.setIsDel(true);
            newVO.setId(id);
            newVO.setUpdateId(userId);
            ret = companyDealerMapper.update(getDO(newVO)) > 0 ? ErrorCode.Success : ErrorCode.Failure;
            if (ErrorCode.Success == ret) {
                dealerVehicleMapper.deleteByClientId(String.valueOf(id));
            }
        }
        return ret;
    }

    public PageCommonVO<CompanyDealerVO> list(SearchCommonVO<CompanyDealerVO> condition) {
        PageCommonVO<CompanyDealerVO> pageCommonVO = new PageCommonVO<>();
        PageHelperPlus.orderBy("create_date desc,DEALER_ORG_ID");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        condition.getFilters().setCompanyNameList(xcmg.device.infra.StringUtil.splitList(condition.getFilters().getCompanyNames()));
        if (condition.getFilters().getCompanyNameList() != null && condition.getFilters().getCompanyNameList().size() == 1) {
            condition.getFilters().setCompanyName(condition.getFilters().getCompanyNameList().get(0));
            condition.getFilters().setCompanyNameList(null);
            condition.getFilters().setCompanyNames(null);
        }
        List<CompanyDealerDO> doList = companyDealerMapper.list4Gc(condition.getFilters());
        List<CompanyDealerVO> voList = new ArrayList<>();
        for (CompanyDealerDO companyDealerDO : doList) {
            if (companyDealerDO == null) {
                continue;
            }
            CompanyDealerVO companyDealerVO = new CompanyDealerVO();
            BeanUtils.copyProperties(companyDealerDO, companyDealerVO);
            if (null != companyDealerDO.getApplyStatus()) {
                companyDealerVO.setApplyStatus(companyDealerDO.getApplyStatus());

                CompanyDealerStatusEnum dealerStatus = CompanyDealerStatusEnum.getDealerStatus(companyDealerDO.getApplyStatus());
                if (null != dealerStatus) {
                    companyDealerVO.setApplyStatusDesc(dealerStatus.getDesc());
                }
            }
//            //获取预付款金额
//            ArapDO arapDO = null;
//            try {
//                arapDO = arapMapper.selectByAccOrgId(condition.getFilters().getOrgId(), companyDealerVO.getDealerOrgId(), 0);
//            } catch (Exception e) {
//                LogHelper.fatal("Too Many Result. orgId:" + condition.getFilters().getOrgId() + ", accOrgId:" + companyDealerVO.getDealerOrgId(), e);
//            }
//            if (null != arapDO) {
//                companyDealerVO.setAdvancePayPrice(arapDO.getPrepPayPrice());
//            }
            voList.add(companyDealerVO);
        }
        pageCommonVO.setPageInfo(new PageInfo<CompanyDealerDO>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    public PageCommonVO<CompanyDealerVO> listForPriceScheme(SearchCommonVO<CompanyDealerVO> condition) {
        PageCommonVO<CompanyDealerVO> pageCommonVO = new PageCommonVO<>();
        PageHelperPlus.orderBy("t1.create_date desc,t1.DEALER_ORG_ID");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        condition.getFilters().setCompanyNameList(xcmg.device.infra.StringUtil.splitList(condition.getFilters().getCompanyNames()));
        if (condition.getFilters().getCompanyNameList() != null && condition.getFilters().getCompanyNameList().size() == 1) {
            condition.getFilters().setCompanyName(condition.getFilters().getCompanyNameList().get(0));
            condition.getFilters().setCompanyNameList(null);
            condition.getFilters().setCompanyNames(null);
        }
        List<CompanyDealerDO> doList = companyDealerMapper.listForPriceScheme(condition.getFilters());
        List<CompanyDealerVO> voList = new ArrayList<>();
        for (CompanyDealerDO companyDealerDO : doList) {
            if (companyDealerDO == null) {
                continue;
            }
            voList.add(getVO(companyDealerDO));
        }
        pageCommonVO.setPageInfo(new PageInfo<CompanyDealerDO>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * 根据当前登录ID过滤
     * 客户授权表信息
     *
     * @param condition
     * @return
     */
    public PageCommonVO<CompanyDealerVO> listByCurrentId(SearchCommonVO<CompanyDealerVO> condition) {
        PageCommonVO<CompanyDealerVO> pageCommonVO = new PageCommonVO<>();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<CompanyDealerDO> doList = companyDealerMapper.listByCurrentId(condition.getFilters());
        List<CompanyDealerVO> voList = new ArrayList<>();
        for (CompanyDealerDO companyDealerDO : doList) {
            if (companyDealerDO == null) {
                continue;
            }
            voList.add(getVO(companyDealerDO));
        }
        pageCommonVO.setPageInfo(new PageInfo<CompanyDealerDO>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * 根据供应商ID或者客户ID
     * 查询不包括当前用户ID的数据
     *
     * @param condition
     * @return
     */
    public PageCommonVO<WarehouseDealerAuthVO> listBySupplierId(SearchCommonVO<CompanyDealerVO> condition) {
        PageCommonVO<WarehouseDealerAuthVO> pageCommonVO = new PageCommonVO<>();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<CompanyDealerDO> doList = companyDealerMapper.listBySupplierId(condition.getFilters());
        List<WarehouseDealerAuthVO> voList = new ArrayList<>();
        for (CompanyDealerDO companyDealerDO : doList) {
            if (companyDealerDO == null) {
                continue;
            }
            WarehouseDealerAuthVO warehouseDealerAuthVO = new WarehouseDealerAuthVO();
            warehouseDealerAuthVO.setDealerId(condition.getFilters().getCurrentId());
            warehouseDealerAuthVO.setDealerAuthId(companyDealerDO.getPlatOrgId());
            warehouseDealerAuthVO.setSupplierId(condition.getFilters().getOrgId());
            warehouseDealerAuthVO.setDealerAuthName(companyDealerDO.getCompanyName());
            //查询客户授权信息
            int cnt = warehouseDealerAuthDOMapper.countByDealerId(condition.getFilters().getCurrentId(),
                    companyDealerDO.getPlatOrgId(),
                    condition.getFilters().getOrgId());
            warehouseDealerAuthVO.setChecked(cnt > 0);
            voList.add(warehouseDealerAuthVO);
        }
        pageCommonVO.setPageInfo(new PageInfo<CompanyDealerDO>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    public ErrorCode invite(CompanyDealerVO companyDealerVO, String userId) {
        CompanyDealerDO companyDealerDO = companyDealerMapper.item(companyDealerVO.getId());
        if (companyDealerDO == null) {
            return ErrorCode.IllegalArument;
        }
        String oldInvitationCode = checkInvite(companyDealerDO.getOrgId(), companyDealerDO.getDealerOrgId());
        if (oldInvitationCode != null) {
            companyDealerVO.setInvitationCode(oldInvitationCode);
            return ErrorCode.Success;
        }
        String invitationCode = generateString(invitationCodeLength);
        companyDealerVO.setInvitationCode(invitationCode);
        CompanyInvitationCodeDO companyInvitationCodeDO = new CompanyInvitationCodeDO();
        companyInvitationCodeDO.setSenderOrgId(companyDealerDO.getOrgId());
        companyInvitationCodeDO.setReceiverOrgId(companyDealerDO.getDealerOrgId());
        companyInvitationCodeDO.setDestPhone(companyDealerDO.getContactTel());
        companyInvitationCodeDO.setInviteType(1);
        companyInvitationCodeDO.setInvitationCode(invitationCode);
        companyInvitationCodeDO.setInviteUserId(userId);
        companyInvitationCodeDO.setCodeState(0);
        companyInvitationCodeDO.setInviteDate(new Date());
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, +inviteExpireDay);
        companyInvitationCodeDO.setExpireDate(cal.getTime());

        int insertRet = companyInvitationCodeMapper.insert(companyInvitationCodeDO);

        if (0 >= insertRet) {
            LogHelper.error("企业邀请码添加失败！", ErrorCode.SqlSyntaxError.getCode());
            return ErrorCode.SqlSyntaxError;
        }

        int updateRet = companyDealerMapper.updateApplyStatus(companyInvitationCodeDO.getSenderOrgId(), companyInvitationCodeDO.getReceiverOrgId(), CompanyConstants.APPLY_STATUS_INVITED);
        if (0 >= updateRet) {
            LogHelper.error("修改企业客户关系中审核状态为已邀请操作失败，数据库异常！", ErrorCode.SqlSyntaxError.getCode());
            return ErrorCode.SqlSyntaxError;
        }
        return ErrorCode.Success;
    }

    /**
     * 通过验证码绑定代理商信息
     *
     * @param orgId          String
     * @param invitationCode String
     * @return ErrorCode
     */
    public ErrorCode boundDealer(String orgId, String invitationCode) {
        CompanyInvitationCodeDO companyInvitationCodeDO = new CompanyInvitationCodeDO();
        companyInvitationCodeDO.setInvitationCode(invitationCode);
        companyInvitationCodeDO = companyInfoService.queryInviteInfo(invitationCode);

        if (null == companyInvitationCodeDO) {
            return ErrorCode.InvitationCodeFail;
        }

        if (orgId.equals(companyInvitationCodeDO.getSenderOrgId())) {
            return ErrorCode.CannotBoundSelf;
        }

        if (!companyInvitationCodeDO.getInviteType().equals(2)) {
            return ErrorCode.InvitationCodeFail;
        }

        //邀请码发送方企业信息
        CompanyInfoVO companyInfoVO = companyInfoService.info(companyInvitationCodeDO.getSenderOrgId());

        if (null == companyInfoVO) {
            return ErrorCode.RelationSupplierCompanyFail;
        }

        int dealerCount = companyDealerMapper.countDealerByInvitationCode(orgId, companyInvitationCodeDO.getSenderOrgId());
        if (dealerCount > 0) {
            return ErrorCode.DealerCompanyRepeat;
        }

        CompanyDealerDO companyDealerDO = companyApplyService.getCompanyDealer(companyInfoVO, orgId);
        boolean ret = mergeCompanyDealerDO(companyDealerDO);

        if (!ret) {
            return ErrorCode.RelationSupplierCompanyFail;
        }

        //更改客户关系
        //修改企业上下游关系表中下游企业状态
        companySupplierMapper.updateApplyStatus(companyInvitationCodeDO.getSenderOrgId(), companyInvitationCodeDO.getReceiverOrgId(), CompanyConstants.APPLY_STATUS_PASS);

        //更新企业客户关系中绑定关系
        companySupplierMapper.boundSupplier(orgId, companyInvitationCodeDO.getSenderOrgId(), companyInvitationCodeDO.getReceiverOrgId());

        companyInvitationCodeDO.setCodeState(1);//邀请码状态为无效
        companyInvitationCodeMapper.update(companyInvitationCodeDO);

        return ErrorCode.Success;
    }

    private String checkInvite(String orgId, String dealerOrgId) {
        CompanyInvitationCodeDO companyInvitationCodeDO = new CompanyInvitationCodeDO();
        companyInvitationCodeDO.setSenderOrgId(orgId);
        companyInvitationCodeDO.setReceiverOrgId(dealerOrgId);
        companyInvitationCodeDO.setInviteDate(new Date());
        companyInvitationCodeDO.setExpireDate(new Date());
        companyInvitationCodeDO.setCodeState(0);
        CompanyInvitationCodeDO inviteInfo = companyInvitationCodeMapper.invitationInfo(companyInvitationCodeDO);
        if (inviteInfo == null) {
            return null;
        }

        if (0 != inviteInfo.getCodeState()) {
            return null;
        }

        return inviteInfo.getInvitationCode();
    }

    private CompanyDealerDO getDO(CompanyDealerVO companyDealerVO) {
        if (companyDealerVO == null) {
            return null;
        }
        CompanyDealerDO companyDealerDO = new CompanyDealerDO();
        BeanUtils.copyProperties(companyDealerVO, companyDealerDO);
        companyDealerDO.setId(companyDealerVO.getId());
        companyDealerDO.setOrgId(companyDealerVO.getOrgId());
        companyDealerDO.setDealerOrgId(companyDealerVO.getDealerOrgId());
        companyDealerDO.setDealerCode(companyDealerVO.getDealerCode());
        companyDealerDO.setCompanyName(companyDealerVO.getCompanyName());
        companyDealerDO.setShortName(companyDealerVO.getShortName());
        companyDealerDO.setAddress(companyDealerVO.getAddress());
        companyDealerDO.setZip(companyDealerVO.getZip());
        companyDealerDO.setFax(companyDealerVO.getFax());
        companyDealerDO.setContact(companyDealerVO.getContact());
        companyDealerDO.setContactTel(companyDealerVO.getContactTel());
        companyDealerDO.setDealerClassId(companyDealerVO.getDealerClassId());
        companyDealerDO.setIsPlatCompany(companyDealerVO.getIsPlatCompany());
        companyDealerDO.setPlatOrgId(companyDealerVO.getPlatOrgId());
        companyDealerDO.setCreateDate(companyDealerVO.getCreateDate());
        companyDealerDO.setCreateId(companyDealerVO.getCreateId());
        companyDealerDO.setUpdateDate(companyDealerVO.getUpdateDate());
        companyDealerDO.setUpdateId(companyDealerVO.getUpdateId());
        companyDealerDO.setIsDel(companyDealerVO.getIsDel());
        companyDealerDO.setDepartemntId(companyDealerVO.getDepartemntId());
        companyDealerDO.setOwerId(companyDealerVO.getOwerId());
        companyDealerDO.setApplyStatus(companyDealerVO.getApplyStatus());
        companyDealerDO.setIsStorage(companyDealerVO.getIsStorage());
        companyDealerDO.setTaxRate(companyDealerVO.getTaxRate());
        return companyDealerDO;
    }

    public CompanyDealerVO getVO(CompanyDealerDO companyDealerVO) {
        if (companyDealerVO == null) {
            return null;
        }
        CompanyDealerVO companyDealerDO = new CompanyDealerVO();
        BeanUtils.copyProperties(companyDealerVO, companyDealerDO);
        companyDealerDO.setId(companyDealerVO.getId());
        companyDealerDO.setOrgId(companyDealerVO.getOrgId());
        companyDealerDO.setDealerOrgId(companyDealerVO.getDealerOrgId());
        companyDealerDO.setDealerCode(companyDealerVO.getDealerCode());
        companyDealerDO.setCompanyName(companyDealerVO.getCompanyName());
        companyDealerDO.setShortName(companyDealerVO.getShortName());
        companyDealerDO.setAddress(companyDealerVO.getAddress());
        companyDealerDO.setZip(companyDealerVO.getZip());
        companyDealerDO.setFax(companyDealerVO.getFax());
        companyDealerDO.setContact(companyDealerVO.getContact());
        companyDealerDO.setContactTel(companyDealerVO.getContactTel());
        companyDealerDO.setDealerClassId(companyDealerVO.getDealerClassId());
        companyDealerDO.setIsPlatCompany(companyDealerVO.getIsPlatCompany());
        companyDealerDO.setPlatOrgId(companyDealerVO.getPlatOrgId());
        companyDealerDO.setCreateDate(companyDealerVO.getCreateDate());
        companyDealerDO.setCreateId(companyDealerVO.getCreateId());
        companyDealerDO.setUpdateDate(companyDealerVO.getUpdateDate());
        companyDealerDO.setUpdateId(companyDealerVO.getUpdateId());
        companyDealerDO.setIsDel(companyDealerVO.getIsDel());
        companyDealerDO.setDepartemntId(companyDealerVO.getDepartemntId());
        companyDealerDO.setOwerId(companyDealerVO.getOwerId());
        companyDealerDO.setDealerClassName(companyDealerVO.getDealerClassName());
        companyDealerDO.setPriceGroup(companyDealerVO.getPriceGroup());
        companyDealerDO.setIsStorage(companyDealerVO.getIsStorage());
        if (null != companyDealerVO.getApplyStatus()) {
            companyDealerDO.setApplyStatus(companyDealerVO.getApplyStatus());

            CompanyDealerStatusEnum dealerStatus = CompanyDealerStatusEnum.getDealerStatus(companyDealerVO.getApplyStatus());
            if (null != dealerStatus) {
                companyDealerDO.setApplyStatusDesc(dealerStatus.getDesc());
            }
        }
        return companyDealerDO;
    }

    public static final String ALL_CHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String generateString(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(ALL_CHAR.charAt(RandomUtils.nextInt(0, ALL_CHAR.length())));
        }
        return sb.toString();
    }

    /**
     * 根据客户分类查询客户列表
     *
     * @param typeId Long
     * @return int
     */
    public Integer countCompanyByType(Long typeId) {
        Integer ret;
        ret = companyDealerMapper.countCompanyByType(typeId);
        return ret;
    }

    public Integer isStorage(String dealerOrgId, String orgId) {
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByOrgId(orgId, dealerOrgId);
        if (companyDealerDO == null) {
            return 0;
        }
        return companyDealerDO.getIsStorage();
    }

    public BigDecimal getDirectLimit(String dealerOrgId, String orgId) {
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByOrgId(orgId, dealerOrgId);
        if (companyDealerDO == null) {
            return BigDecimal.ZERO;
        }
        return companyDealerDO.getDirectLimit();
    }

    public FunctionResult<Object> importDealerExcel(MultipartFile file, String orgId) throws IOException {
        FunctionResult<Object> result = new FunctionResult<>();
        Workbook wb = getWorkbook(file);
        Sheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 13) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("共" + totalCell + "列，导入模板不正确");
            return result;
        }
        List<MaterialsSearchVO> errorDetailVOList = new ArrayList<>();
        doImportDealerExcelCollect(sheet, totalRow, errorDetailVOList, orgId);
        doImportDealerExcelResult(errorDetailVOList, result);
        return result;
    }

    private void doImportDealerExcelCollect(Sheet sheet, int totalRow, List<MaterialsSearchVO> errorDetailVOList,
                                            String orgId) {
        boolean success;
        for (int i = 2; i <= totalRow; i++) {
            Row curRow = sheet.getRow(i);
            MaterialsSearchVO detailVO = new MaterialsSearchVO();
            if (curRow == null) {
                continue;
            }
            String name = StringUtils.trim(getCellValue(curRow, 1));
            String code = getCellValue(curRow, 2);
            String shortName = getCellValue(curRow, 3);
            String priceGroup = getCellValue(curRow, 4);
            String dealerClass = getCellValue(curRow, 5);
            String dealerLevel = getCellValue(curRow, 6);
            String address = getCellValue(curRow, 7);
            String contactUser = getCellValue(curRow, 8);
            String contactTel = getCellValue(curRow, 9);
            String contactFax = getCellValue(curRow, 10);
            String post = getCellValue(curRow, 11);
            String normalFlag = getCellValue(curRow, 12);
            boolean check = checkImportDealerExcel(i, detailVO, errorDetailVOList,
                    name, code, shortName);
            check = checkImportDealerExcel2(i, detailVO, errorDetailVOList,
                    check, priceGroup, address, contactUser);
            if (!check) {
                continue;
            }
            check = checkImportDealerExcel3(i, detailVO, errorDetailVOList,
                    contactTel, contactFax, post, normalFlag);
            if (!check) {
                continue;
            }
            CompanyDealerDO dealerDB = companyDealerMapper.get4Import(orgId, name, code);
            String action;
            if (null == dealerDB) {
                action = "新增";
                dealerDB = new CompanyDealerDO();
                dealerDB.setCompanyName(name);
                dealerDB.setOrgId(orgId);
                dealerDB.setDealerCode(code);
                dealerDB.setDealerOrgId(commonGenService.textIdWithException());
                dealerDB.setCreateDate(new Date());
                dealerDB.setIsDel(false);
                dealerDB.setIsPlatCompany(false);
                dealerDB.setShortName(shortName);
                dealerDB.setPriceGroup(priceGroup);
                dealerDB.setAddress(address);
                dealerDB.setContact(contactUser);
                dealerDB.setContactTel(contactTel);
                dealerDB.setFax(contactFax);
                dealerDB.setZip(post);
                dealerDB.setDealerClassName(dealerClass);
                dealerDB.setDealerLevelName(dealerLevel);
                dealerDB.setUpdateDate(new Date());
                dealerDB.setNormalFlag(Integer.valueOf(normalFlag));
                success = addCompanyDealerDO(dealerDB);

            } else {
                action = "更新";
                dealerDB.setShortName(shortName);
                dealerDB.setPriceGroup(priceGroup);
                dealerDB.setAddress(address);
                dealerDB.setContact(contactUser);
                dealerDB.setContactTel(contactTel);
                dealerDB.setFax(contactFax);
                dealerDB.setZip(post);
                dealerDB.setUpdateDate(new Date());
                dealerDB.setDealerClassName(dealerClass);
                dealerDB.setDealerLevelName(dealerLevel);
                // 只能更改一次
                if (null == dealerDB.getNormalFlag()) {
                    dealerDB.setNormalFlag(Integer.valueOf(normalFlag));
                }
                success = companyDealerMapper.update(dealerDB) > 0;
            }
            if (!success) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark(action + "失败");
                errorDetailVOList.add(detailVO);
                continue;
            }
        }
    }

    private void doImportDealerExcelResult(List<MaterialsSearchVO> errorDetailVOList, FunctionResult<Object> result) {
        if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
            result.setValue(new ArrayList<>());
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
    }

    private boolean checkImportDealerExcel3(int i, MaterialsSearchVO detailVO, List<MaterialsSearchVO> errorDetailVOList,
                                            String contactTel, String contactFax, String post, String normalFlag) {
        if (contactTel.length() > 20) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("联系方式长度过长");
            errorDetailVOList.add(detailVO);
            return false;
        }
        if (contactFax.length() > 20) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("传真长度过长");
            errorDetailVOList.add(detailVO);
            return false;
        }
        if (post.length() > 20) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("邮编长度过长");
            errorDetailVOList.add(detailVO);
            return false;
        }
        if (StringUtils.isEmpty(normalFlag)) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("请填写客户状态(正常维护或流失)");
            errorDetailVOList.add(detailVO);
            return false;
        }
        return true;
    }

    private boolean checkImportDealerExcel2(int i, MaterialsSearchVO detailVO, List<MaterialsSearchVO> errorDetailVOList,
                                            boolean check, String priceGroup, String address, String contactUser) {
        if (!check) {
            return check;
        }
        if (priceGroup.length() > 2) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("价格组长度过长");
            errorDetailVOList.add(detailVO);
            return false;
        }
        if (address.length() > 190) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("地址长度过长");
            errorDetailVOList.add(detailVO);
            return false;
        }
        if (contactUser.length() > 40) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("联系人长度过长");
            errorDetailVOList.add(detailVO);
            return false;
        }
        return true;
    }

    private boolean checkImportDealerExcel(int i, MaterialsSearchVO detailVO, List<MaterialsSearchVO> errorDetailVOList,
                                           String name, String code, String shortName) {
        if (StringUtil.isNullOrEmpty(name)) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("客户名称不能为空");
            errorDetailVOList.add(detailVO);
            return false;
        }
        if (name.length() > 150) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("客户名称长度过长");
            errorDetailVOList.add(detailVO);
            return false;
        }
        if (code.length() > 20) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("客户编号长度过长");
            errorDetailVOList.add(detailVO);
            return false;
        }
        if (shortName.length() > 90) {
            detailVO.setErrorRow(i + 1);
            detailVO.setRemark("客户简称长度过长");
            errorDetailVOList.add(detailVO);
            return false;
        }
        return true;
    }

    private Workbook getWorkbook(MultipartFile file) throws IOException {
        try {
            InputStream in = file.getInputStream();
            return new HSSFWorkbook(in);
        } catch (Exception ex) {
            InputStream in = file.getInputStream();
            return new XSSFWorkbook(in);
        }
    }

    private String getCellValue(Row curRow, int i) {
        String value = "";
        if (curRow.getCell(i) != null) {
            curRow.getCell(i).setCellType(CellType.STRING);
            value = curRow.getCell(i).getStringCellValue();
        }
        return value == null ? "" : value;
    }

    public void downloadDealerExcel() {
        try {
            FileUtil.downLoadFile(response, filePath, templateDealer);
        } catch (Exception e) {
            log.error("", e);
            throw new CommonBusiExceptions(e.getMessage());
        }
    }


    /**
     * 根据符号隔开的多个客户名简写搜索对应的客户全称
     *
     * @param shortPurchaseNames
     * @return
     */
    public List<String> listFullNamesByShortName(String orgId, String shortPurchaseNames) {
        List<String> purchaseNamesList = new ArrayList<>();
        List<String> purchaseNames = xcmg.device.infra.StringUtil.getStrSplitList(shortPurchaseNames);
        if (CollectionUtils.isNotEmpty(purchaseNames)) {
            for (String shortName : purchaseNames) {
                List<String> names = companyDealerMapper.listFullNamesByShortName(orgId, shortName);
                if (CollectionUtils.isEmpty(names)) {
                    continue;
                }
                purchaseNamesList.addAll(names);
            }
        }

        return purchaseNamesList;
    }

    //获取常规代理商
    public PageCommonVO<CompanyDealerVO> getRegularAgent(SearchCommonVO<CompanyDealerVO> condition) {
        PageCommonVO<CompanyDealerVO> pageCommonVO = new PageCommonVO<>();
        PageHelperPlus.orderBy("create_date,id desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<CompanyDealerDO> doList = companyDealerMapper.getRegularAgent(condition.getFilters());
        List<CompanyDealerVO> voList = new ArrayList<>();
        for (CompanyDealerDO companyDealerDO : doList) {
            CompanyDealerVO companyDealerVO = new CompanyDealerVO();
            BeanUtils.copyProperties(companyDealerDO, companyDealerVO);
            voList.add(companyDealerVO);
        }
        pageCommonVO.setPageInfo(new PageInfo<CompanyDealerDO>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * 如果客户创建时间在6个月内，默认是正常维护客户
     * 如果超过六个月，且无有效订单，则改为流失
     * 如果已流失，6个月内又有了新增有效订单，则改为正常维护
     *
     * @param companyDealerDO
     * @param orgId
     * @author wangyog 2020-03-03
     */
    @Async
    public void updateNormalFlag(CompanyDealerDO companyDealerDO, String orgId) {
        if (DateUtil.addMonth(companyDealerDO.getCreateDate(), 6).after(new Date()) && !companyDealerDO.isNormal()) {
            companyDealerDO.setNormalFlag(CompanyDealerDO.NORMAL_FLAG_YES);
            companyDealerMapper.update(companyDealerDO);
            return;
        }

        Integer sixMonthOrderQty = saleIntentionMapper.countSixMonthOrder(orgId, companyDealerDO.getPlatOrgId(), companyDealerDO.getDealerOrgId());
        if (sixMonthOrderQty > 0 && !companyDealerDO.isNormal()) {
            companyDealerDO.setNormalFlag(CompanyDealerDO.NORMAL_FLAG_YES);
            companyDealerMapper.update(companyDealerDO);
            return;
        }
    }

    /**
     * 导出客户车辆数据
     *
     * @param condition
     * @throws Exception
     * @author wangyong 2020-03-05
     */
    public void exportDealerVehicles(CompanyDealerVO condition) {
        Integer count = dealerVehicleMapper.countDealerVehicle(condition);
        if (count == 0) {
            throw new CommonBusiExceptions("暂无客户车辆数据");
        }
        List<DealerVehicleExportVO> dataList = new ArrayList<>();
        if (count <= EXPORT_PAGE_SIZE) {
            dataList = dealerVehicleMapper.listDealerVehicle(condition);
        } else {
            int times = count / EXPORT_PAGE_SIZE + 1;
            for (int i = 0; i < times; i++) {
                PageHelperPlus.startPage(i + 1, EXPORT_PAGE_SIZE, "company_name");
                dataList.addAll(dealerVehicleMapper.listDealerVehicle(condition));
            }
        }
        invokeExport(dataList);
    }

    private void invokeExport(List<DealerVehicleExportVO> vosList) {
        String title = "客户车辆数据导出";
        String[] rowsName = new String[]{"序号", "客户名称", "客户编码", "客户分类", "客户分级", "客户状态", "联系人", "联系方式", "客户地址", "品牌", "机型",
                "车号", "整机赠送额度（保养）", "整机赠送额度（通用）", "初始已用额度（保养）", "初始已用额度（通用）", "系统已用额度（保养）", "系统已用额度（通用）",
                "剩余额度（保养）", "剩余额度（通用）", "是否停用", "保修状态", "备注"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < vosList.size(); i++) {
            DealerVehicleExportVO exportDO = vosList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = exportDO.getCompanyName();
            objs[2] = exportDO.getDealerCode();
            objs[3] = exportDO.getDealerClassName();
            objs[4] = exportDO.getDealerLevelName();
            objs[5] = exportDO.getNormalDesc();
            objs[6] = exportDO.getContact();
            objs[7] = exportDO.getContactTel();
            objs[8] = exportDO.getAddress();
            objs[9] = exportDO.getBrandName();
            objs[10] = exportDO.getModel();
            objs[11] = exportDO.getCarNo();
            objs[12] = exportDO.getMaintenanceSendAmount();
            objs[13] = exportDO.getUniversalSendAmount();
            objs[14] = exportDO.getInitialMaintenanceUseAmount();
            objs[15] = exportDO.getInitialUniversalUseAmount();
            objs[16] = exportDO.getMaintenanceUseAmount();
            objs[17] = exportDO.getUniversalUseAmount();
            objs[18] = exportDO.getMaintenanceLaveAmount();
            objs[19] = exportDO.getUniversalLaveAmount();
            objs[20] = exportDO.getDisableDesc();
            objs[21] = exportDO.getWarrantyStatus();
            objs[22] = exportDO.getRemark();
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }


    public Integer countDealerByOrgIdAndPlatOrgId(String orgId, String platOrgId) {
        if (org.apache.commons.lang.StringUtils.isEmpty(orgId) || org.apache.commons.lang.StringUtils.isEmpty(platOrgId)) {
            return 0;
        }
        Integer count = companyDealerMapper.countByOrgIdAndPlatOrgId(orgId, platOrgId);
        if (count == null) {
            return 0;
        }
        return count;
    }

    public CompanyDealerVO queryByParam(CompanyDealerVO param) {
        CompanyDealerDO ddo = companyDealerMapper.queryOneByPlatOrgIdAndTypes(param.getPlatOrgId(), param.getDealerTypeList());
        if (null != ddo) {
            return BeanUtil.do2bo(ddo, CompanyDealerVO.class);
        }
        return null;
    }

    public String initDealer(String ynOrgId) {
        //查询表中云内下面所有的营销中心code
        List<String> codes = companyDealerMapper.queryAllMarketingCenterCode(ynOrgId);
        if (CollectionUtils.isEmpty(codes)) {
            return "查询营销中心失败";
        }
        StringBuilder msg = new StringBuilder();
        for (String code : codes) {
            //类别（1、核心企业2、代理商（20二级代理商）  3、供应商4、承运商5、服务站（50二级服务站） 6、代理商&服务站）
            List<CompanyDealerDO> fwzList = companyDealerMapper.queryCompanyDealerDOListByCode(code, 5);
            List<CompanyDealerDO> dlsList = companyDealerMapper.queryCompanyDealerDOListByCode(code, 2);
            if (CollectionUtils.isEmpty(fwzList) || CollectionUtils.isEmpty(dlsList)) {
                msg.append(code + " 下面的“代理商”和“服务站”没有要建立关系的数据\n");
                continue;
            }
            for (CompanyDealerDO fwz : fwzList) {
                for (CompanyDealerDO dls : dlsList) {
                    try {
                        bindFwzAndDlsRelation(fwz, dls);
                    } catch (Exception e) {
                        log.warn("fwz:{}\ndls:{}\n绑定异常！ ", fwz, dls, e);
                        msg.append(code + " :fwz=").append(fwz.getCompanyName()).append(" ,\n dls=").append(dls.getCompanyName()).append(e.getMessage()).append("\n");
                    }
                }
            }
        }
        return msg.toString();
    }

    /**
     * 根据两个platOrgid绑定他们的关系
     *
     * @param orgId
     * @param platOrgid
     */
    public void bindDealerSupplierRelation(String orgId, String platOrgid) {
        CompanyDealerDO fwz = companyDealerMapper.itemByPlatOrgId(orgId);
        if (null == fwz) {
            throw new CommonBusiExceptions("业务伙伴查询失败");
        }
        CompanyDealerDO dls = companyDealerMapper.itemByPlatOrgId(platOrgid);
        if (null == dls) {
            throw new CommonBusiExceptions("供应商信息在业务伙伴查询失败");
        }
        bindFwzAndDlsRelation(fwz, dls);
    }

    private void bindFwzAndDlsRelation(CompanyDealerDO fwz, CompanyDealerDO dls) {
        Long newFwzId = commonGenService.longIdWithException();
        CompanyDealerDO newFwz = BeanUtil.do2bo(fwz, CompanyDealerDO.class);
        newFwz.setId(newFwzId);
        newFwz.setOrgId(dls.getPlatOrgId());
        newFwz.setCreateId(dls.getCreateId());
        //检查是否符合添加条件，不符合抛异常
        checkCompanyDealerDOExist(newFwz);
        //在代理商的业务伙伴中添加服务站
        addCompanyDealerDO(newFwz);
        //生成邀请码
        String invitationCode = genInvitationCode(newFwz);
        //服务站在供应商功能中绑定
        ErrorCode r = companySupplierService.boundSupplier(fwz.getPlatOrgId(), invitationCode);
        if (0 != r.getCode()) {
            throw new CommonBusiExceptions("绑定失败：" + r.getDesc());
        }
    }

    /**
     * 根据新建的伙伴创建邀请码
     *
     * @param newFwz
     * @return
     */
    private String genInvitationCode(CompanyDealerDO newFwz) {
        String invitationCode = generateString(invitationCodeLength);
        CompanyInvitationCodeDO companyInvitationCodeDO = new CompanyInvitationCodeDO();
        companyInvitationCodeDO.setSenderOrgId(newFwz.getOrgId());
        companyInvitationCodeDO.setReceiverOrgId(newFwz.getDealerOrgId());
        companyInvitationCodeDO.setDestPhone(newFwz.getContactTel());
        companyInvitationCodeDO.setInviteType(1);
        companyInvitationCodeDO.setInvitationCode(invitationCode);
        companyInvitationCodeDO.setInviteUserId(newFwz.getCreateId());
        companyInvitationCodeDO.setCodeState(0);
        companyInvitationCodeDO.setInviteDate(new Date());
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, +inviteExpireDay);
        companyInvitationCodeDO.setExpireDate(cal.getTime());
        companyInvitationCodeMapper.insert(companyInvitationCodeDO);
        companyDealerMapper.updateApplyStatus(companyInvitationCodeDO.getSenderOrgId(), companyInvitationCodeDO.getReceiverOrgId(), CompanyConstants.APPLY_STATUS_INVITED);
        return invitationCode;
    }

    /**
     * 校验新的业务伙伴是否可以添加
     *
     * @param newFwz
     */
    private void checkCompanyDealerDOExist(CompanyDealerDO newFwz) {
        CompanyDealerDO companyDealerDO = new CompanyDealerDO();
        companyDealerDO.setOrgId(newFwz.getOrgId());
        companyDealerDO.setCompanyName(newFwz.getCompanyName());
        companyDealerDO.setDealerCode(newFwz.getDealerCode());
        Integer nameCount = companyDealerMapper.nameCount(companyDealerDO);
        if (nameCount > 0) {
            throw new CommonBusiExceptions("业务伙伴名称已经存在");
        }
        if (companyDealerDO.getDealerCode() != null) {
            Integer codeCount = companyDealerMapper.dealerCodeCount(companyDealerDO);
            if (codeCount > 0) {
                throw new CommonBusiExceptions(ErrorCode.DealerCodeDuplicated.getDesc());
            }
        }
    }
}
